//
//  M3U8DownloadManage.m
//  LocalHttpServerExample
//
//  Created by Lin Eidan on 13-9-6.
//  Copyright (c) 2013年 taomee. All rights reserved.
//

#import "M3U8DownloadManage.h"
#import "M3U8DownloadConfig.h"
#import "DownloadGetData.h"
#import "M3U8Handle.h"
#import "AppDelegate.h"
#import "VideoObj.h"

@interface M3U8DownloadManage ()

@property (assign, nonatomic) BOOL isUserCancel;
@property (strong, nonatomic) NSTimer *retryTimer;

@end


@implementation M3U8DownloadManage

-(id)initWithM3U8Handle:(M3U8Handle *)m3u8Handle andVideoObj:(VideoObj *)obj{
    self = [super init];
    if (self) {
        self.VideoObj = obj;
        self.contentId=obj.contentId;
        self.curNum=obj.currentPlayIndex;
        self.totalDur=m3u8Handle.totalDur;
        self.segmentsArray=m3u8Handle.segmentsArray;
        self.saveToPath=m3u8Handle.localM3U8FileFolder;
        self.episodeId=obj.episodeId;
        self.retryTime=0;
    }
    return self;
}

-(void)startDownloadVideo{
    [self.retryTimer invalidate];
    
    if ([[DownloadGetData sharedInstance] theNetworkTypeIsNone]) {
        if ([self.delegate respondsToSelector:@selector(m3U8DownloadManageAllSegmentsHasDownloadFailed:andVideoObj:)]) {
            [self.delegate m3U8DownloadManageAllSegmentsHasDownloadFailed:self andVideoObj:self.VideoObj];
        }
        return;
    }
    
    if (self.VideoObj.isLoading) {
        
        //点击暂停，isLoading肯定为No，但是M3u8handle的Request还没有取消掉，可能会继续下载，这里多一层判断，保证其不会下载。
        self.isUserCancel = NO;
        self.hasDownloadDur=0.0;
        self.hasFailedDur=0.0;
        
        self.downloadArray=[[NSMutableArray alloc] init];
        for (int i=0; i<self.segmentsArray.count; i++) {
            M3U8SegmentInfo *info=[self.segmentsArray objectAtIndex:i];
            NSString *fileName = [NSString stringWithFormat:@"%@%d",kSegmentIdFlag,i];
            
//            if (i == 0 ) {
//               
//                info.segmentURL =@"";
//                if (self.retryTime == 5) {
//                    info.segmentURL = @"http://manhua.tmcdn.net/cartoon/49/49ef1d6ea2b2510a775453f7a8fbc3d8";
//                    NSLog(@"%@",info.segmentURL);
//                }
//                
//            }
            
            SegmentDownloadManage *manage=[[SegmentDownloadManage alloc] initWithDownloadURL:info.segmentURL andFileName:fileName andSaveToPath:self.saveToPath andFileDur:info.segmentLength andVideoObj:self.VideoObj];
            manage.delegate=self;
            [self.downloadArray addObject:manage];
        }
//        NSLog(@"true start");
        [self startTheDownloadFirstSegment];
    }
    
}


-(void)startTheDownloadFirstSegment{
    if (self.isUserCancel) {
        return;
    }
    if ([[DownloadGetData sharedInstance] theNetworkTypeIsNone]) {
        if ([self.delegate respondsToSelector:@selector(m3U8DownloadManageAllSegmentsHasDownloadFailed:andVideoObj:)]) {
            [self.delegate m3U8DownloadManageAllSegmentsHasDownloadFailed:self andVideoObj:self.VideoObj];
        }
        return;
    }
    if (self.downloadArray.count > 0 ) {  //有才去执行,一次只执行一个。
        SegmentDownloadManage *temp = (SegmentDownloadManage *)[self.downloadArray objectAtIndex:0];
        [temp startSegmentDownload];
    }
}

-(void)pauseDownloadVideo{
    self.isUserCancel = YES;
    [self.retryTimer invalidate];
}

-(void)segmentDownloadManageFinish:(SegmentDownloadManage *)segmentDownloadManage andSegmentDur:(float)segmentDur andIsSuccess:(BOOL)isSuccess{
    [self.downloadArray removeObject:segmentDownloadManage];
    
    if (isSuccess) {
//        NSLog(@"segment success");
        self.hasDownloadDur+=segmentDur;
        float per=self.hasDownloadDur/self.totalDur;
        
        if ([self.delegate respondsToSelector:@selector(m3U8DownloadManage:andAllSegmentsHasDownloadPer:andVideoObj:)]) {
            [self.delegate m3U8DownloadManage:self andAllSegmentsHasDownloadPer:per andVideoObj:self.VideoObj];
        }
        
    }else{
        self.hasFailedDur += segmentDur;
    }
    
    if (self.hasFailedDur >0 && self.downloadArray.count == 0) {
        if (self.isUserCancel) {   //用户主动取消
            if ([self.delegate respondsToSelector:@selector(m3U8DownloadManageAllSegmentsHasDownloadFailed:andVideoObj:)]) {
                [self.delegate m3U8DownloadManageAllSegmentsHasDownloadFailed:self andVideoObj:self.VideoObj];
            }
        }else{
            
            if (self.retryTime <= 4) {  //如果没重试过，那么重试一次
                self.retryTime++;
                self.retryTimer = [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(startDownloadVideo) userInfo:NO repeats:YES];
            }else{
                if ([self.delegate respondsToSelector:@selector(m3U8DownloadManageAllSegmentsHasDownloadFailed:andVideoObj:)]) {
                    [self.delegate m3U8DownloadManageAllSegmentsHasDownloadFailed:self andVideoObj:self.VideoObj];
                }
            }

        }
        
    }
    
    //顺序不能换
    [self startTheDownloadFirstSegment];
    
    if ((int)self.hasDownloadDur >= (int)self.totalDur) {
        if ([self.delegate respondsToSelector:@selector(m3U8DownloadManageAllSegmentsHasDownloadSuccessed:andVideoObj:)]) {
            [self.delegate m3U8DownloadManageAllSegmentsHasDownloadSuccessed:self andVideoObj:self.VideoObj];
        }
    }
    
}


@end
